package byx.container.annotation.demo.PublishSubscribeDemo;

import byx.container.annotation.annotation.Register;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Register
public class MessageBus {
    private final Map<String, List<Subscriber>> subscriberMap;
    private final List<Subscriber> defaultSubscribers;

    public MessageBus(List<Subscriber> subscribers) {
        subscriberMap = subscribers.stream()
                .filter(s -> s.getClass().isAnnotationPresent(Topic.class))
                .collect(Collectors.groupingBy(s -> s.getClass().getAnnotation(Topic.class).value()));
        defaultSubscribers = subscribers.stream()
                .filter(s -> !s.getClass().isAnnotationPresent(Topic.class))
                .collect(Collectors.toList());
    }

    public void send(String topic, String msg) {
        if (subscriberMap.containsKey(topic)) {
            subscriberMap.get(topic).forEach(s -> s.consume(msg));
        } else {
            defaultSubscribers.forEach(s -> s.consume(msg));
        }
    }
}
